﻿//copyright © kaveh.shahbazian@gmail.com and http://www.codeplex.com/site/users/view/Cread 2010-2011 (see license.txt)
using System;
using System.IO;
using System.Linq;
using System.Xml;
using System.Diagnostics;
using System.Collections.ObjectModel;

namespace Funtastic
{
    static class Settings
    {
        private static Layout _windowLayout = Layout.Vertical;
        private static string _fspath = "";
        private static ObservableCollection<Document> recentDocuments = new ObservableCollection<Document>();
        private static string apppath = AppDomain.CurrentDomain.BaseDirectory;

        // prevents Funtatic from writing Settings.xml each time
        private static bool settingsChanged = false;

        public static string FsPath
        {
            get
            {
                return _fspath;
            }
            set
            {
                settingsChanged = true;
                _fspath = value;
            }
        }
        public static Layout WindowLayout
        {
            get { return _windowLayout; }
            set
            {
                _windowLayout = value;
                settingsChanged = true;
            }
        }

        public static void SaveValues()
        {
            if (settingsChanged)
            {
                XmlTextWriter myXmlTextWriter = new XmlTextWriter(apppath + "\\Settings.xml", System.Text.Encoding.UTF8);
                myXmlTextWriter.Formatting = Formatting.Indented;
                myXmlTextWriter.WriteStartDocument(false);
                myXmlTextWriter.WriteStartElement("Settings");

                // Main settings
                myXmlTextWriter.WriteStartElement("Main");
                myXmlTextWriter.WriteElementString("FsPath", _fspath);
                myXmlTextWriter.WriteElementString("WindowLayout", _windowLayout.ToString());
                myXmlTextWriter.WriteEndElement();

                // Recent documents
                myXmlTextWriter.WriteStartElement("RecentDocuments");
                foreach (Document recentDocument in RecentDocuments)
                {
                    myXmlTextWriter.WriteStartElement("Document");
                    
                    myXmlTextWriter.WriteElementString("FullName", recentDocument.FullName.ToString());
                    myXmlTextWriter.WriteElementString("Date", recentDocument.Date.ToString());
                    
                    myXmlTextWriter.WriteEndElement();
                }
                myXmlTextWriter.WriteEndElement();

                myXmlTextWriter.WriteEndElement();
                myXmlTextWriter.WriteEndDocument();

                myXmlTextWriter.Flush();
                myXmlTextWriter.Close();
            }
        }

        public static void LoadValues()
        {
            if (!File.Exists(apppath + "\\Settings.xml"))
                return;

            try
            {
                // XML lesen
                var doc = new XmlDocument();
                doc.Load(apppath + "\\Settings.xml");
                XmlElement root = doc.DocumentElement;
                // Main
                XmlNode settings = root.FirstChild;
                _fspath = settings["FsPath"].InnerText;
                Layout.TryParse(settings["WindowLayout"].InnerText, true, out _windowLayout);

                // recent documents
                XmlNode recentDocsXML = root.ChildNodes[1];
                foreach (XmlNode adoc in recentDocsXML.ChildNodes)
                {
                    recentDocuments.Add(new Document() { FullName = adoc["FullName"].InnerText, Date = DateTime.Parse(adoc["Date"].InnerText) });
                }
            }
            catch (Exception)
            {
#if DEBUG
                Debug.WriteLine("error while parsing Settings.xml");

                // Testitems
                //recentDocuments.Add(new Document { FullName = "C:\\Users\\Stefan_2\\Desktop\\AgentUtils.fsx", Date = DateTime.Now });
                //recentDocuments.Add(new Document { FullName = "C:\\Users\\Stefan_2\\Desktop\\Server.fsx", Date = DateTime.Now });
#endif
            }
        }

        public static ObservableCollection<Document> RecentDocuments
        {
            get { return (recentDocuments); }
        }
        public static bool AddRecentDocument(Document doc) // returns wheter the addition was succesful or not
        {
            // test whether item is already in list
            var results = from adoc in recentDocuments
                          where adoc.FullName.StartsWith(doc.FullName)
                          select adoc;
            if (results.Count() > 0)
                return false;

            recentDocuments.Add(doc);
            settingsChanged = true;

            // remove one item if there are more than 5
            if (recentDocuments.Count > 5)
            {
                var oldestItem = (from item in recentDocuments
                                 orderby item.Date
                                 select item).First();
                recentDocuments.Remove(oldestItem);
            }
            return true;
        }
    }

    public enum Layout
    {
        Horizontal = 0,
        Vertical,
        Hidden
    }
}
